package com.hongye.proprietary.listener;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.hongye.common.constant.OrderStatusConstant;
import com.hongye.proprietary.entity.HongyeOrderEntity;
import com.hongye.proprietary.fegin.PayFeignService;
import com.hongye.proprietary.service.HongyeOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author lins
 * @date 2021/10/20 9:14
 */
@Slf4j
@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderCloseListener {
    @Autowired
    private HongyeOrderService orderService;
    @Autowired
    PayFeignService payFeignService;
    @RabbitHandler
    public void closeOrder(HongyeOrderEntity orderEntity, Channel channel, Message message) throws IOException {
        try {
            //关闭订单
            log.info("收到关闭订单的消息>>>>订单编号>>>>{}" , orderEntity.getOrderNumber());
            //System.out.println("收到关闭订单的消息>>>>订单编号>>>>" + orderEntity.getOrderNumber());
            HongyeOrderEntity entity = orderService.getById(orderEntity.getOrderId());
            if (!entity.getOrderStatus().equals(OrderStatusConstant.ORDER_PAYED)){
                //通过交易流水号查询支付宝该订单支付状态
                AlipayTradeQueryResponse alipayTradeQueryResponse = payFeignService.transactionQuery(orderEntity.getOrderNumber());
                if (!alipayTradeQueryResponse.isSuccess()){
                    //交易失败  修改订单状态为已关闭
                    orderService.closeOrder(orderEntity);
                    log.info("关闭订单>>>>订单编号>>>>{}" , orderEntity.getOrderNumber());
                }else {
                    //如果交易成功  修改订单状态为已支付
                    orderService.modifyOrderStatus(orderEntity);
                    log.info("修改订单>>>>订单编号>>>>{}" , orderEntity.getOrderNumber());
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
